package com.hdd.biz.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdd.biz.member.dto.APPMemberLoginRequest;
import com.hdd.biz.member.dto.APPMemberRequest;
import com.hdd.biz.member.entity.Member;
import com.hdd.biz.member.mapper.MemberMapper;
import com.hdd.biz.member.service.APPMemberService;
import com.hdd.dto.SuperResponse;
import com.hdd.utils.JsonUtil;
import com.hdd.utils.http.HttpClient;
import com.hdd.utils.http.OkHttpResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class APPMemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements APPMemberService {

    @Value("${wx.appid}")
    private String appid;

    @Value("${wx.secret}")
    private String secret;

    @Override
    public SuperResponse weixinLogin(APPMemberLoginRequest request) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + request.getOpenCode() + "&grant_type=authorization_code";
        OkHttpResponse<String> response = HttpClient.doGet(url);
        Map<String, Object> dataMap = JsonUtil.toMap(response.getData());
        if (dataMap.containsKey("unionid")) {
            dataMap.put("errcode", 0);
              Member member = findMemberUnionId((String) dataMap.get("unionid"));
//            dataMap.putAll(buildResult(sysUser));
        }else if(dataMap.containsKey("openid")){
            dataMap.put("errcode", 0);
              Member member = findUserByXcxOpenid((String) dataMap.get("openid"));
//            dataMap.putAll(buildResult(sysUser));
        }
        return null;
    }



    @Override
    public SuperResponse findUserById(APPMemberRequest request) {
        SuperResponse response = new SuperResponse();
        QueryWrapper<Member> queryWrapper = new QueryWrapper<Member>();
        queryWrapper.eq("user_id",request.getUserId());
        response.setItem(baseMapper.selectOne(queryWrapper));
        return response;
    }




    public Member findMemberUnionId(String unionId){
        Member member = null;
        QueryWrapper<Member> queryWrapper = new QueryWrapper<Member>();
        queryWrapper.eq("union_id",unionId);
        return baseMapper.selectOne(queryWrapper);
    }


    public Member findUserByXcxOpenid(String openId){
        Member member = null;
        QueryWrapper<Member> queryWrapper = new QueryWrapper<Member>();
        queryWrapper.eq("xcx_openid",openId);
        return baseMapper.selectOne(queryWrapper);
    }


}
